import 'dart:io';


import 'key_mix_test.dart';

List<String> IgnoreFileNames = ['app.dart', 'comm_key_def', 'key_mix'];

void main(List<String> args) async {
  // var args= [];
  if (args.isEmpty) {
    await targetDirectory(Directory("../FastLending2/LManage"));
  } else if (args[0] == 're') {
    await targetDirectoryRe(Directory("../FastLending2/LManage"));
  }
  print("success");
  // convertHx(File("./lib/ap/com/http/HttpRequest.dart"));
}

targetDirectory(Directory directory) async {
  final List<FileSystemEntity> entities = directory.listSync();

  for (final entity in entities) {
    if (entity is File) {
      convertHx(entity);
    } else if (entity is Directory) {
      targetDirectory(entity);
    }
  }
}

void convertHx(File file) {
  final RegExp regex = RegExp(r'''['"](.*?)['"].hx''');
  if (!file.path.contains('.swift')) return;
  String fileContent = file.readAsStringSync();
  final Iterable<RegExpMatch> matches = regex.allMatches(fileContent);

  for (final match in matches) {
    String originalFileName1 = match.group(1) ?? "";
    String orTxt = match.group(0).toString();
    if (originalFileName1.contains("\"")) {
      originalFileName1 =
          originalFileName1.substring(originalFileName1.lastIndexOf("\"") + 1);
      orTxt = "\"$originalFileName1\".hx";
    }
    String newFileName = originalFileName1.hx;

    if (isNotEmpty(newFileName)) {
      print("convert File:${file.path}");
      fileContent = fileContent.replaceAll(orTxt, "\"$newFileName\".rhx");
    }
  }
  file.writeAsStringSync(fileContent);
}

targetDirectoryRe(Directory directory) async {
  final List<FileSystemEntity> entities = directory.listSync();

  for (final entity in entities) {
    if (entity is File) {
      convertHxRe(entity);
    } else if (entity is Directory) {
      targetDirectoryRe(entity);
    }
  }
}

void convertHxRe(File file) {
  final RegExp regex = RegExp(r'''['"](.*?)['"].rhx''');
  if (!file.path.contains('.swift')) return;
  String fileContent = file.readAsStringSync();
  final Iterable<RegExpMatch> matches = regex.allMatches(fileContent);

  for (final match in matches) {
    String originalFileName1 = match.group(1) ?? "";
    String orTxt = match.group(0).toString();
    if (originalFileName1.contains("\"")) {
      originalFileName1 =
          originalFileName1.substring(originalFileName1.lastIndexOf("\"") + 1);
      orTxt = "\"$originalFileName1\".rhx";
    }
    String newFileName = originalFileName1.reHx;

    if (isNotEmpty(newFileName)) {
      print("convert File:${file.path}");
      fileContent = fileContent.replaceAll(orTxt, "\"$newFileName\".hx");
    }
  }
  file.writeAsStringSync(fileContent);
}
///判断字符是否为空
  bool isEmpty(str) {
if (str == null) return true;
if (str.toString() == 'null') return true;
return str
    .toString()
    .isEmpty;
}

///判断字符是否不为空
  bool isNotEmpty(str) {
return !isEmpty(str);
}